package com.easyidea.its.util;

import java.util.Map;

import ognl.DefaultTypeConverter;

public class EnumTypeConverter extends DefaultTypeConverter {

	/**
	 * Converts the given object to a given type. How this is to be done is
	 * implemented in toClass. The OGNL context, o and toClass are given. This
	 * method should be able to handle conversion in general without any context
	 * or object specified.
	 * 
	 * @param context - OGNL context under which the conversion is being done
	 * @param o - the object to be converted
	 * @param toClass - the class that contains the code to convert to
	 *            enumeration
	 * @return Converted value of type declared in toClass or
	 *         TypeConverter.NoConversionPossible to indicate that the
	 *         conversion was not possible.
	 */
	public Object convertValue(Map context, Object o, Class toClass) {
		if (o instanceof String[]) {
			return convertFromString(((String[]) o)[0], toClass);
		} else if (o instanceof String) {
			return convertFromString((String) o, toClass);
		}

		return super.convertValue(context, o, toClass);
	}

	/**
	 * Converts one or more String values to the specified class.
	 * 
	 * @param value - the String values to be converted, such as those submitted
	 *            from an HTML form
	 * @param toClass - the class to convert to
	 * @return the converted object
	 * @see com.opensymphony.webwork.util.WebWorkTypeConverter#convertFromString(java.util.Map,
	 *      String[], Class)
	 */
	public Object convertFromString(String value, Class toClass) {
		return Enum.valueOf(toClass, value);
	}
}
